﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChoViet.CMS.Properties;
using ChoViet.CMS.ViewModels;
using ChoViet.Lib.Common;
using ChoViet.Lib.Helpers;
using ChoViet.Model;
namespace ChoViet.CMS.Controllers
{
    public class CategoryController : BaseController
    {

        /// <summary>
        /// Created by: VietLV
        /// Created date: 01/05/2012
        /// Description: Manage Category controller
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        //[OutputCache(CacheProfile="LeftCateCache")]
        public ActionResult LeftCategories(Demand demand, Category activeCategory, City city, AdAttribute adAttribute, AdAttributeValue adAttributeValue,int cusTypeId)
        { 
            ChoVietDataContext db = new ChoVietDataContext();
            try
			{
                var rootCategories = db.Categories.Where(e => e.ParentID == null).OrderBy(e=> e.Name).ToList();
                return View(new CategoryIndexLeftViewModel
				{
					Demand = demand,
					RootCategories = rootCategories,
                    ActiveCategory = activeCategory,
				//	Cities = cities,
                    ActiveCity = city,
                    AdAttribute = adAttribute,
                    AdAttributeValue = adAttributeValue,
                    CusTypeId = cusTypeId
				});
			}
			catch { throw; }
		}
        
        #region GET: /Category/IndexCms
        [RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult IndexCms()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (UserManager.CheckRole(RoleSystem.Dictionary))
                {
                    string order = UserState.getUserStateFromRequest("category.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("category.orderDir", "orderDir", "desc").ToString();
                    int parentID = Convert.ToInt32(UserState.getUserStateFromRequest("category.parentID", "parentID", 0));
                //    var categories = eDataContext.Categories.OrderBy(string.Format("{0} {1}", order, orderDir)).ToList();

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;
                    return View(new CategoryIndexViewModel
                    {
                        CategoryBuiltTree = Model.CategoryManager.BuiltCombobox(0),
                        ParentCatIDs = eDataContext.Categories.Where(e => e.ParentID == null || e.ParentID == 0).Select(e => e.ID.ToString()).ToList()   
                    });
                }
                else
                {
                    Messages.AddFlashMessage("Bạn không có quyền truy cập ứng dụng này");
                    ViewData["MessageInfo"] = "Bạn không có quyền truy cập ứng dụng này";
                    return View();
                }
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Category/DetailsCms
        [RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult DetailsCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            var param = eDataContext.Categories.FirstOrDefault(e => e.ID == id);
            return View(param);
        }
        #endregion

        #region GET: /Category/CreateCms
        [RoleHelper(Roles = RoleSystem.Dictionary)]

        public ActionResult CreateCms()
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var listParent = eDataContext.Categories.Where(c => c.ParentID == null).ToList();

                return View(new CategoryEditViewModel() { ParrentCatrgories = listParent});
            }
            finally { eDataContext.Dispose();}
        }
        #endregion

        #region POST: /Category/CreateCms
        [RoleHelper(Roles = RoleSystem.Dictionary)]
        [HttpPost] 
        public ActionResult CreateCms(CategoryEditViewModel c)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                UpdateModel(c);
                c.Category.CreatedBy = UserManager.GetUserId();
                c.Category.CreatedDate = DateTime.Now;

                eDataContext.Categories.InsertOnSubmit(c.Category);
                eDataContext.SubmitChanges();
                //Image display
                HttpPostedFileBase fileImage = Request.Files["catimage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    c.Category.ImagePath = Uploads.UploadFile(fileImage, Settings.Default.CategoryAvatarPath,Settings.Default.SiteRootPath,c.Category.ID.ToString());
                }
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                Messages.AddFlashMessage("Thêm chuyên mục thành công!");
                return RedirectToAction("IndexCms");
            }
            catch
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                return View();
            }
        }
        #endregion

        #region GET: /Category/EditCms/5
        [RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult EditCms(int id)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                var param = new CategoryEditViewModel();
                param.Category = eDataContext.Categories.Where(e => e.ID == id).SingleOrDefault();
                param.ParrentCatrgories = eDataContext.Categories.Where(e => e.ParentID == null || e.ParentID ==0).ToList();
                return View(param);
            }
            catch (Exception exp)
            {
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Category/EditCms/5
        [HttpPost]
        [RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult EditCms(int id, CategoryEditViewModel c)
        {
            ChoVietDataContext eDataContext = new ChoVietDataContext();
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                c.Category = eDataContext.Categories.Where(cat => cat.ID == id).SingleOrDefault();
                UpdateModel(c);
                c.Category.ModifyBy = UserManager.GetUserId();
                c.Category.ModifyDate= DateTime.Now;
                eDataContext.SubmitChanges();
                //Image display
                HttpPostedFileBase fileImage = Request.Files["catimage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    //Delete old icon
                    Uploads.DeleteFile(Settings.Default.AdminRootPath + c.Category.ImagePath);
                    //var nextid = (eDataContext.Ads.Max(e => e.ID) + 1).ToString();
                    c.Category.ImagePath = Uploads.UploadFile(fileImage, Settings.Default.CategoryAvatarPath,Settings.Default.SiteRootPath, c.Category.ID.ToString());
                }
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                Messages.AddFlashMessage("Sửa chuyên mục thành công!");
                return RedirectToAction("IndexCms");
                }
            catch(Exception exp)
            {
                eDataContext.Transaction.Rollback();
                eDataContext.Dispose();
                ViewData["MessageInfo"] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Department/DeleteCms/5
        [RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult DeleteCms(int id)
       {
           ChoVietDataContext eDataContext = new ChoVietDataContext();
           try
           {
               if (UserManager.CheckRole(RoleSystem.Dictionary))
               {
                   var item = eDataContext.Categories.Single(e => e.ID == id);
                   return View(item);
               }
               else
               {
                   Messages.AddErrorFlashMessage("Bạn không có quyền truy cập ứng dụng này");
                   ViewData["MessageInfo"] = "Bạn không có quyền truy cập ứng dụng này";
                   return View();
               }
           }
           catch (Exception exp)
           {
               ViewData["MessageInfo"] = exp.Message;
               return View();
           }
       }
        #endregion

        #region POST: /Department/DeleteCms/5
        [HttpPost]
        [RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult DeleteCms(int id, FormCollection collection)
       {
           ChoVietDataContext eDataContext = new ChoVietDataContext();
           try
           {
               if (UserManager.CheckRole(RoleSystem.Dictionary))
               {
                   var item = eDataContext.Categories.Single(e => e.ID == id);
                   if (item != null)
                   {
                       eDataContext.Categories.DeleteOnSubmit(item);
                       eDataContext.SubmitChanges();
                   }
                   return RedirectToAction("IndexCms");
               }
               else
               {
                   ViewData["MessageInfo"] = "Bạn không có quyền truy cập ứng dụng này!";
                   return View();
               }
           }
           catch (Exception exp)
           {
               ViewData["MessageInfo"] = exp.Message;
               return View();
           }
       }
       #endregion
    }
}
